//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package project_chat_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas/api-server/api_common"
	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/chat_dao"
	"atomgit.com/openlinksaas/api-server/dao/user_dao"
	"atomgit.com/openlinksaas/api-server/utils"
	"atomgit.com/openlinksaas/proto-gen-go.git/notices/notices_chat"
	"atomgit.com/openlinksaas/proto-gen-go.git/project_chat_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

func (apiImpl *ProjectChatApiImpl) SendMsg(ctx context.Context, req *project_chat_api.SendMsgRequest) (*project_chat_api.SendMsgResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_chat_api.SendMsgResponse{
			Code:   project_chat_api.SendMsgResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	//检查权限
	_, _, _, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_chat_api.SendMsgResponse{
			Code:   project_chat_api.SendMsgResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_chat_api.SendMsgResponse{
			Code:   project_chat_api.SendMsgResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}

	exist, err := chat_dao.GroupDao.Exist(ctx, req.ProjectId, req.ChatGroupId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_chat_api.SendMsgResponse{
			Code:   project_chat_api.SendMsgResponse_CODE_NO_CHAT_GROUP,
			ErrMsg: "沟通群不存在",
		}, nil
	}

	exist, err = chat_dao.GroupMemberDao.Exist(ctx, req.ProjectId, req.ChatGroupId, sessionItem.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_chat_api.SendMsgResponse{
			Code:   project_chat_api.SendMsgResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	msgId := uuid.NewString()
	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = dao.MsgDataDao.Insert(sessCtx, &dao.MsgDataDBItem{
			MsgId:        msgId,
			Content:      req.Content,
			CreateUserId: sessionItem.UserId,
			CreateTime:   nowTime,
			HasChanged:   false,
		})
		if err != nil {
			return nil, err
		}
		//增加聊天组index
		err = chat_dao.GroupMsgIndexDao.Insert(sessCtx, &chat_dao.GroupMsgIndexDbItem{
			MsgId:       msgId,
			ChatGroupId: req.ChatGroupId,
			TimeStamp:   nowTime,
		})
		if err != nil {
			return nil, err
		}
		//更新lastMsg
		err = chat_dao.GroupDao.UpdateLastMsgId(sessCtx, req.ProjectId, req.ChatGroupId, msgId)
		if err != nil {
			return nil, err
		}
		//更新lastMsgTime
		err = chat_dao.GroupMemberDao.UpdateLastMsgTime(sessCtx, req.ProjectId, req.ChatGroupId, nowTime)
		if err != nil {
			return nil, err
		}
		//增加未读数量
		err = chat_dao.GroupMemberDao.IncUnreadCount(sessCtx, req.ProjectId, req.ChatGroupId)
		if err != nil {
			return nil, err
		}
		return &project_chat_api.SendMsgResponse{
			Code:      project_chat_api.SendMsgResponse_CODE_OK,
			ChatMsgId: msgId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	//发送通知
	memberItemList, err := chat_dao.GroupMemberDao.ListMember(ctx, req.ProjectId, req.ChatGroupId)
	if err == nil {
		for _, memberItem := range memberItemList {
			go api_common.SendNoticeToUser(context.Background(), memberItem.UserId, &notices_chat.NewMsgNotice{
				ProjectId:   req.ProjectId,
				ChatGroupId: req.ChatGroupId,
				ChatMsgId:   msgId,
			})
		}
	}
	return ret.(*project_chat_api.SendMsgResponse), nil
}

func (apiImpl *ProjectChatApiImpl) UpdateMsgContent(ctx context.Context, req *project_chat_api.UpdateMsgContentRequest) (*project_chat_api.UpdateMsgContentResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_chat_api.UpdateMsgContentResponse{
			Code:   project_chat_api.UpdateMsgContentResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	//检查权限
	_, _, _, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_chat_api.UpdateMsgContentResponse{
			Code:   project_chat_api.UpdateMsgContentResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_chat_api.UpdateMsgContentResponse{
			Code:   project_chat_api.UpdateMsgContentResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}

	exist, err := chat_dao.GroupDao.Exist(ctx, req.ProjectId, req.ChatGroupId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_chat_api.UpdateMsgContentResponse{
			Code:   project_chat_api.UpdateMsgContentResponse_CODE_NO_CHAT_GROUP,
			ErrMsg: "沟通群不存在",
		}, nil
	}

	exist, err = chat_dao.GroupMemberDao.Exist(ctx, req.ProjectId, req.ChatGroupId, sessionItem.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_chat_api.UpdateMsgContentResponse{
			Code:   project_chat_api.UpdateMsgContentResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	msgIndexItem, err := chat_dao.GroupMsgIndexDao.Get(ctx, req.ChatGroupId, req.ChatMsgId)
	if err != nil {
		return &project_chat_api.UpdateMsgContentResponse{
			Code:   project_chat_api.UpdateMsgContentResponse_CODE_NO_MSG,
			ErrMsg: "沟通消息不存在",
		}, nil
	}
	nowTime := time.Now().UnixNano() / 1e6
	if msgIndexItem.TimeStamp+_UPDATE_MSG_AGE < nowTime {
		return &project_chat_api.UpdateMsgContentResponse{
			Code:   project_chat_api.UpdateMsgContentResponse_CODE_TIME_EXPIRE,
			ErrMsg: "超过修改时间限制",
		}, nil
	}

	msgItem, err := dao.MsgDataDao.Get(ctx, req.ChatMsgId)
	if err != nil {
		return &project_chat_api.UpdateMsgContentResponse{
			Code:   project_chat_api.UpdateMsgContentResponse_CODE_NO_MSG,
			ErrMsg: "沟通消息不存在",
		}, nil
	}
	if msgItem.CreateUserId != sessionItem.UserId {
		return &project_chat_api.UpdateMsgContentResponse{
			Code:   project_chat_api.UpdateMsgContentResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = dao.MsgDataDao.Update(ctx, req.ChatMsgId, req.Content)
		if err != nil {
			return nil, err
		}
		return &project_chat_api.UpdateMsgContentResponse{
			Code: project_chat_api.UpdateMsgContentResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	//发送通知
	memberItemList, err := chat_dao.GroupMemberDao.ListMember(ctx, req.ProjectId, req.ChatGroupId)
	if err == nil {
		for _, memberItem := range memberItemList {
			go api_common.SendNoticeToUser(context.Background(), memberItem.UserId, &notices_chat.UpdateMsgNotice{
				ProjectId:   req.ProjectId,
				ChatGroupId: req.ChatGroupId,
				ChatMsgId:   req.ChatMsgId,
			})
		}
	}
	return ret.(*project_chat_api.UpdateMsgContentResponse), nil
}

func (apiImpl *ProjectChatApiImpl) ListMsg(ctx context.Context, req *project_chat_api.ListMsgRequest) (*project_chat_api.ListMsgResponse, error) {
	emptyList := []*project_chat_api.ChatMsgInfo{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_chat_api.ListMsgResponse{
			Code:    project_chat_api.ListMsgResponse_CODE_WRONG_SESSION,
			ErrMsg:  "会话不存在",
			MsgList: emptyList,
		}, nil
	}
	//检查权限
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_chat_api.ListMsgResponse{
			Code:    project_chat_api.ListMsgResponse_CODE_NO_PROJECT,
			ErrMsg:  "项目不存在",
			MsgList: emptyList,
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_chat_api.ListMsgResponse{
			Code:    project_chat_api.ListMsgResponse_CODE_NO_PERMISSION,
			ErrMsg:  "没有权限",
			MsgList: emptyList,
		}, nil
	} else if err != nil {
		return nil, err
	}

	exist, err := chat_dao.GroupDao.Exist(ctx, req.ProjectId, req.ChatGroupId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_chat_api.ListMsgResponse{
			Code:    project_chat_api.ListMsgResponse_CODE_NO_CHAT_GROUP,
			ErrMsg:  "沟通群不存在",
			MsgList: emptyList,
		}, nil
	}

	if !(projectItem.OwnerUserId == sessionItem.UserId || roleItem.BasicInfo.Admin) {
		exist, err := chat_dao.GroupMemberDao.Exist(ctx, req.ProjectId, req.ChatGroupId, sessionItem.UserId)
		if err != nil {
			return nil, err
		}
		if !exist {
			return &project_chat_api.ListMsgResponse{
				Code:    project_chat_api.ListMsgResponse_CODE_NO_PERMISSION,
				ErrMsg:  "没有权限",
				MsgList: emptyList,
			}, nil
		}
	}

	refTime := time.Now().UnixNano() / 1e6
	if req.RefChatMsgId != "" {
		msgIndexItem, err := chat_dao.GroupMsgIndexDao.Get(ctx, req.ChatGroupId, req.RefChatMsgId)
		if err != nil {
			return nil, err
		}
		refTime = msgIndexItem.TimeStamp
	}

	msgIndexItemList, err := chat_dao.GroupMsgIndexDao.List(ctx, req.ChatGroupId, refTime, req.ListMsgType, req.Limit)
	if err != nil {
		return nil, err
	}
	msgIdList := []string{}
	for _, msgIndexItem := range msgIndexItemList {
		msgIdList = append(msgIdList, msgIndexItem.MsgId)
	}
	msgItemList, err := dao.MsgDataDao.ListById(ctx, msgIdList)
	if err != nil {
		return nil, err
	}
	msgItemMap := map[string]*dao.MsgDataDBItem{}
	userIdList := []string{}
	for _, msgItem := range msgItemList {
		msgItemMap[msgItem.MsgId] = msgItem
		userIdList = append(userIdList, msgItem.CreateUserId)
	}
	//获取用户信息
	userItemList, err := user_dao.UserInfoDao.ListById(ctx, userIdList)
	if err != nil {
		return nil, err
	}
	userItemMap := map[string]*user_dao.UserInfoDbItem{}
	for _, userItem := range userItemList {
		userItemMap[userItem.UserId] = userItem
	}
	//生成结果
	msgInfoList := []*project_chat_api.ChatMsgInfo{}
	for _, msgIndexItem := range msgIndexItemList {
		msgItem, ok := msgItemMap[msgIndexItem.MsgId]
		if !ok {
			continue
		}
		msgInfo := &project_chat_api.ChatMsgInfo{
			ChatMsgId:   msgItem.MsgId,
			ChatGroupId: msgIndexItem.ChatGroupId,
			Content:     msgItem.Content,
			SendUserId:  msgItem.CreateUserId,
			SendTime:    msgItem.CreateTime,
			HasChanged:  msgItem.HasChanged,
		}
		userItem, ok := userItemMap[msgItem.CreateUserId]
		if ok {
			msgInfo.SendDisplayName = userItem.BasicInfo.DisplayName
			msgInfo.SendLogoUri = userItem.BasicInfo.LogoUri
		}
		msgInfo.ChangeDeadLineTime = msgItem.CreateTime + _UPDATE_MSG_AGE
		msgInfoList = append(msgInfoList, msgInfo)
	}

	return &project_chat_api.ListMsgResponse{
		Code:    project_chat_api.ListMsgResponse_CODE_OK,
		MsgList: msgInfoList,
	}, nil
}

func (apiImpl *ProjectChatApiImpl) ListAllLastMsg(ctx context.Context, req *project_chat_api.ListAllLastMsgRequest) (*project_chat_api.ListAllLastMsgResponse, error) {
	emptyList := []*project_chat_api.ChatMsgInfo{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_chat_api.ListAllLastMsgResponse{
			Code:    project_chat_api.ListAllLastMsgResponse_CODE_WRONG_SESSION,
			ErrMsg:  "会话不存在",
			MsgList: emptyList,
		}, nil
	}
	//检查权限
	_, _, _, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_chat_api.ListAllLastMsgResponse{
			Code:    project_chat_api.ListAllLastMsgResponse_CODE_NO_PROJECT,
			ErrMsg:  "项目不存在",
			MsgList: emptyList,
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_chat_api.ListAllLastMsgResponse{
			Code:    project_chat_api.ListAllLastMsgResponse_CODE_NO_PERMISSION,
			ErrMsg:  "没有权限",
			MsgList: emptyList,
		}, nil
	} else if err != nil {
		return nil, err
	}

	memberItemList, err := chat_dao.GroupMemberDao.ListChatGroup(ctx, req.ProjectId, sessionItem.UserId, "")
	if err != nil {
		return nil, err
	}
	groupIdList := []string{}
	for _, memberItem := range memberItemList {
		groupIdList = append(groupIdList, memberItem.ChatGroupId)
	}
	groupItemList, err := chat_dao.GroupDao.ListById(ctx, req.ProjectId, groupIdList)
	if err != nil {
		return nil, err
	}

	msgIdList := []string{}
	for _, groupItem := range groupItemList {
		if groupItem.LastMsgId == "" {
			continue
		}
		msgIdList = append(msgIdList, groupItem.LastMsgId)
	}

	msgItemList, err := dao.MsgDataDao.ListById(ctx, msgIdList)
	if err != nil {
		return nil, err
	}
	msgItemMap := map[string]*dao.MsgDataDBItem{}
	userIdList := []string{}
	for _, msgItem := range msgItemList {
		msgItemMap[msgItem.MsgId] = msgItem
		userIdList = append(userIdList, msgItem.CreateUserId)
	}
	//获取用户信息
	userItemList, err := user_dao.UserInfoDao.ListById(ctx, userIdList)
	if err != nil {
		return nil, err
	}
	userItemMap := map[string]*user_dao.UserInfoDbItem{}
	for _, userItem := range userItemList {
		userItemMap[userItem.UserId] = userItem
	}
	//生成结果
	msgInfoList := []*project_chat_api.ChatMsgInfo{}
	for _, groupItem := range groupItemList {
		msgItem, ok := msgItemMap[groupItem.LastMsgId]
		if !ok {
			continue
		}
		msgInfo := &project_chat_api.ChatMsgInfo{
			ChatMsgId:   msgItem.MsgId,
			ChatGroupId: groupItem.ChatGroupId,
			Content:     msgItem.Content,
			SendUserId:  msgItem.CreateUserId,
			SendTime:    msgItem.CreateTime,
			HasChanged:  msgItem.HasChanged,
		}
		userItem, ok := userItemMap[msgItem.CreateUserId]
		if ok {
			msgInfo.SendDisplayName = userItem.BasicInfo.DisplayName
			msgInfo.SendLogoUri = userItem.BasicInfo.LogoUri
		}

		msgInfo.ChangeDeadLineTime = msgItem.CreateTime + _UPDATE_MSG_AGE
		msgInfoList = append(msgInfoList, msgInfo)
	}

	return &project_chat_api.ListAllLastMsgResponse{
		Code:    project_chat_api.ListAllLastMsgResponse_CODE_OK,
		MsgList: msgInfoList,
	}, nil
}

func (apiImpl *ProjectChatApiImpl) GetMsg(ctx context.Context, req *project_chat_api.GetMsgRequest) (*project_chat_api.GetMsgResponse, error) {
	emptyMsg := &project_chat_api.ChatMsgInfo{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_chat_api.GetMsgResponse{
			Code:   project_chat_api.GetMsgResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
			Msg:    emptyMsg,
		}, nil
	}
	//检查权限
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_chat_api.GetMsgResponse{
			Code:   project_chat_api.GetMsgResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
			Msg:    emptyMsg,
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_chat_api.GetMsgResponse{
			Code:   project_chat_api.GetMsgResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
			Msg:    emptyMsg,
		}, nil
	} else if err != nil {
		return nil, err
	}

	exist, err := chat_dao.GroupDao.Exist(ctx, req.ProjectId, req.ChatGroupId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_chat_api.GetMsgResponse{
			Code:   project_chat_api.GetMsgResponse_CODE_NO_CHAT_GROUP,
			ErrMsg: "沟通群不存在",
			Msg:    emptyMsg,
		}, nil
	}

	if !(projectItem.OwnerUserId == sessionItem.UserId || roleItem.BasicInfo.Admin) {
		exist, err := chat_dao.GroupMemberDao.Exist(ctx, req.ProjectId, req.ChatGroupId, sessionItem.UserId)
		if err != nil {
			return nil, err
		}
		if !exist {
			return &project_chat_api.GetMsgResponse{
				Code:   project_chat_api.GetMsgResponse_CODE_NO_PERMISSION,
				ErrMsg: "没有权限",
				Msg:    emptyMsg,
			}, nil
		}
	}

	//检查msg是否存在
	exist, err = chat_dao.GroupMsgIndexDao.Exist(ctx, req.ChatGroupId, req.ChatMsgId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_chat_api.GetMsgResponse{
			Code:   project_chat_api.GetMsgResponse_CODE_NO_MSG,
			ErrMsg: "沟通内容不存在",
			Msg:    emptyMsg,
		}, nil
	}

	msgItem, err := dao.MsgDataDao.Get(ctx, req.ChatMsgId)
	if err != nil {
		return &project_chat_api.GetMsgResponse{
			Code:   project_chat_api.GetMsgResponse_CODE_NO_MSG,
			ErrMsg: "沟通内容不存在",
			Msg:    emptyMsg,
		}, nil
	}

	//获取用户信息
	userItemList, err := user_dao.UserInfoDao.ListById(ctx, []string{msgItem.CreateUserId})
	if err != nil {
		return nil, err
	}

	//生成结果
	msgInfo := &project_chat_api.ChatMsgInfo{
		ChatMsgId:   req.ChatMsgId,
		ChatGroupId: req.ChatGroupId,
		Content:     msgItem.Content,
		SendUserId:  msgItem.CreateUserId,
		SendTime:    msgItem.CreateTime,
		HasChanged:  msgItem.HasChanged,
	}
	if len(userItemList) > 0 {
		msgInfo.SendDisplayName = userItemList[0].BasicInfo.DisplayName
		msgInfo.SendLogoUri = userItemList[0].BasicInfo.LogoUri
	}
	msgInfo.ChangeDeadLineTime = msgItem.CreateTime + _UPDATE_MSG_AGE

	return &project_chat_api.GetMsgResponse{
		Code: project_chat_api.GetMsgResponse_CODE_OK,
		Msg:  msgInfo,
	}, nil
}

func (apiImpl *ProjectChatApiImpl) GetLastMsg(ctx context.Context, req *project_chat_api.GetLastMsgRequest) (*project_chat_api.GetLastMsgResponse, error) {
	emptyMsg := &project_chat_api.ChatMsgInfo{}

	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_chat_api.GetLastMsgResponse{
			Code:   project_chat_api.GetLastMsgResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
			Msg:    emptyMsg,
		}, nil
	}
	//检查权限
	projectItem, _, roleItem, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_chat_api.GetLastMsgResponse{
			Code:   project_chat_api.GetLastMsgResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
			Msg:    emptyMsg,
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_chat_api.GetLastMsgResponse{
			Code:   project_chat_api.GetLastMsgResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
			Msg:    emptyMsg,
		}, nil
	} else if err != nil {
		return nil, err
	}

	groupItem, err := chat_dao.GroupDao.Get(ctx, req.ProjectId, req.ChatGroupId)
	if err != nil {
		return &project_chat_api.GetLastMsgResponse{
			Code:   project_chat_api.GetLastMsgResponse_CODE_NO_CHAT_GROUP,
			ErrMsg: "沟通群不存在",
			Msg:    emptyMsg,
		}, nil
	}

	if !(projectItem.OwnerUserId == sessionItem.UserId || roleItem.BasicInfo.Admin) {
		exist, err := chat_dao.GroupMemberDao.Exist(ctx, req.ProjectId, req.ChatGroupId, sessionItem.UserId)
		if err != nil {
			return nil, err
		}
		if !exist {
			return &project_chat_api.GetLastMsgResponse{
				Code:   project_chat_api.GetLastMsgResponse_CODE_NO_PERMISSION,
				ErrMsg: "没有权限",
				Msg:    emptyMsg,
			}, nil
		}
	}

	if groupItem.LastMsgId == "" {
		return &project_chat_api.GetLastMsgResponse{
			Code:   project_chat_api.GetLastMsgResponse_CODE_OK,
			HasMsg: false,
			Msg:    emptyMsg,
		}, nil
	}

	exist, err := chat_dao.GroupMsgIndexDao.Exist(ctx, req.ChatGroupId, groupItem.LastMsgId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_chat_api.GetLastMsgResponse{
			Code:   project_chat_api.GetLastMsgResponse_CODE_NO_MSG,
			ErrMsg: "沟通内容不存在",
			Msg:    emptyMsg,
		}, nil
	}

	msgItem, err := dao.MsgDataDao.Get(ctx, groupItem.LastMsgId)
	if err != nil {
		return &project_chat_api.GetLastMsgResponse{
			Code:   project_chat_api.GetLastMsgResponse_CODE_NO_MSG,
			ErrMsg: "沟通内容不存在",
			Msg:    emptyMsg,
		}, nil
	}

	//获取用户信息
	userItemList, err := user_dao.UserInfoDao.ListById(ctx, []string{msgItem.CreateUserId})
	if err != nil {
		return nil, err
	}

	//生成结果
	msgInfo := &project_chat_api.ChatMsgInfo{
		ChatMsgId:   groupItem.LastMsgId,
		ChatGroupId: req.ChatGroupId,
		Content:     msgItem.Content,
		SendUserId:  msgItem.CreateUserId,
		SendTime:    msgItem.CreateTime,
		HasChanged:  msgItem.HasChanged,
	}
	if len(userItemList) > 0 {
		msgInfo.SendDisplayName = userItemList[0].BasicInfo.DisplayName
		msgInfo.SendLogoUri = userItemList[0].BasicInfo.LogoUri
	}
	msgInfo.ChangeDeadLineTime = msgItem.CreateTime + _UPDATE_MSG_AGE

	return &project_chat_api.GetLastMsgResponse{
		Code:   project_chat_api.GetLastMsgResponse_CODE_OK,
		HasMsg: true,
		Msg:    msgInfo,
	}, nil
}

func (apiImpl *ProjectChatApiImpl) ClearUnread(ctx context.Context, req *project_chat_api.ClearUnreadRequest) (*project_chat_api.ClearUnreadResponse, error) {
	sessionItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &project_chat_api.ClearUnreadResponse{
			Code:   project_chat_api.ClearUnreadResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	//检查权限
	_, _, _, err := utils.GetProjectMemberRole(ctx, req.ProjectId, sessionItem.UserId)
	if err == utils.ErrNoProject {
		return &project_chat_api.ClearUnreadResponse{
			Code:   project_chat_api.ClearUnreadResponse_CODE_NO_PROJECT,
			ErrMsg: "项目不存在",
		}, nil
	} else if err == utils.ErrNoRole {
		return &project_chat_api.ClearUnreadResponse{
			Code:   project_chat_api.ClearUnreadResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	} else if err != nil {
		return nil, err
	}

	exist, err := chat_dao.GroupDao.Exist(ctx, req.ProjectId, req.ChatGroupId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_chat_api.ClearUnreadResponse{
			Code:   project_chat_api.ClearUnreadResponse_CODE_NO_CHAT_GROUP,
			ErrMsg: "沟通群不存在",
		}, nil
	}
	exist, err = chat_dao.GroupMemberDao.Exist(ctx, req.ProjectId, req.ChatGroupId, sessionItem.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &project_chat_api.ClearUnreadResponse{
			Code:   project_chat_api.ClearUnreadResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = chat_dao.GroupMemberDao.ClearUnreadCount(sessCtx, req.ProjectId, req.ChatGroupId, sessionItem.UserId)
		if err != nil {
			return nil, err
		}
		return &project_chat_api.ClearUnreadResponse{
			Code: project_chat_api.ClearUnreadResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*project_chat_api.ClearUnreadResponse), nil
}
